<?php
class Admin_Model_Organs extends Zend_Db_Table_Abstract
{
	protected $_name = 'organs';
	
	public function getOrgans() {
        $select = $this->_db->select()
                        ->from($this->_name)
                        ->order('name ASC')
                        ->order('acronym ASC')
                        ->order('date_created ASC');
                        
        $results = $this->getAdapter()->fetchAll($select);
        return $results;
	}
	
	public function findOrgans($name,$acronym) {
        $select = $this->_db->select()
                        ->from($this->_name)
                        ->order('name ASC')
                        ->order('acronym ASC');
                              
		if($name) {
			$select->where('lower(name) LIKE ?', '%'.$name.'%');
		}
		if($acronym) {
			$select->where('lower(acronym) LIKE ?', '%'.$acronym.'%');
		}

        $results = $this->getAdapter()->fetchAll($select); 
        
        return $results;
	}

	public function getOrganById($id)
	{
		$id = (int)$id;
		$row = $this->fetchRow('id = ' . $id);
		
		if (!$row) {
			return false;
		} else {
			return $row->toArray();
		}
	}
	
	public function getOrganByName($name)
	{
		$row = $this->fetchRow("name = '".$name."' ");
		
		if (!$row) {
			return false;
		} else {
			return $row->toArray();
		}
	}

	public function addOrgan($name,$acronym,$date_created)
	{
		$data = array(
			'name'		=> $name, 
			'acronym'	=> $acronym,
			'date_created' 	=> $date_created,
		);
		$this->insert($data);
	}

	public function updateOrgan($id,$name,$acronym)
	{
		$data = array(
			'name'		=> $name, 
			'acronym'	=> $acronym,
		);
		$this->update($data, 'id = '. $id);
	}

	public function deleteOrgan($id)
	{
		$this->delete('id =' . (int)$id);
	}

	public function isUniqueOrganName($name)
	{
		$select = $this->select();
		$select->from($this->_name, 'COUNT(*) AS num')
		->where('name = ?', $name);

		return ($this->fetchRow($select)->num == 0) ? true : false;
	}
	
	public function isUniqueOrganAcronym($acronym)
	{
		$select = $this->select();
		$select->from($this->_name, 'COUNT(*) AS num')
		->where('acronym = ?', $acronym);

		return ($this->fetchRow($select)->num == 0) ? true : false;
	}

}